// scrape-price.js
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
const { DOMParser } = require('xmldom');
const fs = require('fs');
const path = require('path');

puppeteer.use(StealthPlugin());

(async () => {
  let browser;
  try {
    browser = await puppeteer.launch({
      headless: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-blink-features=AutomationControlled',
        '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'
      ]
    });

    const page = await browser.newPage();

    await page.setExtraHTTPHeaders({
      'Accept': 'application/xml, text/xml, */*',
      'Accept-Language': 'en-US,en;q=0.9',
    });

    console.log('正在请求...');
    await page.goto('https://api2.codexfield.co/api/swap/priceHis?pageNum=0&pageSize=999999999', {
      waitUntil: 'networkidle0',
      timeout: 30000
    });

    const xml = await page.content();
    console.log('获取成功');

    // 解析 XML
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xml);

    const contentNodes = xmlDoc.getElementsByTagName('content');
    const result = [];

    for (let i = 1; i < contentNodes.length; i++) {
      const item = contentNodes[i];
      const id = item.getElementsByTagName('id')[0]?.textContent || '';
      const symbol = item.getElementsByTagName('symbol')[0]?.textContent || '';
      const price = item.getElementsByTagName('price')[0]?.textContent || '';
      const time = item.getElementsByTagName('time')[0]?.textContent || '';

      result.push({
        id,
        symbol,
        price,
        time
      });
    }

    // ✅ 生成文件名：price_YYYY-MM-DD.json
    const dateStr = new Date().toISOString().split('T')[0];
    const filename = `price_${dateStr}.json`;
    const filepath = path.join(__dirname, filename);

    // ✅ 写入文件
    fs.writeFileSync(filepath, JSON.stringify(result, null, 2), 'utf-8');
    console.log(`✅ 数据已保存到: ${filepath}`);

  } catch (error) {
    console.error('抓取失败:', error.message);
    process.exit(1);
  } finally {
    if (browser) await browser.close();
  }
})();